package com.sixbro.common.domain;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;

import static com.sixbro.common.domain.ApiResponseCode.SUCCESS;
import static com.sixbro.common.domain.ApiResponseCode.SYSTEM_EXECUTION_ERROR;

/**
 * <p>
 *
 * </p>
 *
 * @author: Mr.Lu
 * @since: 2021/6/15 11:13
 */
@Data
@Accessors(chain = true)
@ApiModel(value = "统一返回结果封装",description = "接口返回统一结果")
public class ApiResponse<T> implements Serializable {

    @ApiModelProperty(value = "状态码")
    private String code;

    @ApiModelProperty(value = "响应信息")
    private String message;

    @ApiModelProperty(value = "后端返回结果")
    private T data;

    @ApiModelProperty(value = "請求路徑")
    private String uri;

    @ApiModelProperty(value = "响应时间戳")
    private long timestamp;

    private ApiResponse(String code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
        this.timestamp = System.currentTimeMillis();
    }

    public static <T> ApiResponse<T> success() {
        return success(null);
    }

    public static <T> ApiResponse<T> success(T data) {
        return result(SUCCESS.getCode(), SUCCESS.getMessage(), data);
    }

    public static <T> ApiResponse<T> failed() {
        return failed(SYSTEM_EXECUTION_ERROR);
    }

    public static <T> ApiResponse<T> failed(String message){
        return result(SYSTEM_EXECUTION_ERROR.getCode(), message, null);
    }

    public static <T> ApiResponse<T> failed(IResponseCode responseCode){
        return result(responseCode.getCode(), responseCode.getMessage(), null);
    }

    private static <T> ApiResponse<T> result(IResponseCode responseCode, T data) {
        return result(responseCode.getCode(), responseCode.getMessage(), data);
    }

    private static <T> ApiResponse<T> result(String code, String message, T data) {
        ApiResponse<T> apiResponse = new ApiResponse<T>(code, message, data);
        return apiResponse;
    }
}